

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Application {
	
	static int append = 0;
	
	public static void main(String[] args) throws IOException, InterruptedException {
		//文件
		File file = new File("F:/demo2.txt");
		if (file.exists()) {
			file.delete();
			file.createNewFile();
		}
		FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
		BufferedWriter bw = new BufferedWriter(fw);
		
		long startTime = System.currentTimeMillis();
		
		//记录条数
		final int count = 10000000;
		final int batch = 1000;
		final int lop = count/batch;
		final CountDownLatch countDown = new CountDownLatch(lop);
		
		ThreadPoolExecutor service = new ThreadPoolExecutor(1000, 1000, 0, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>());
		Random random = new Random(5);
		for(int start = 0; start < lop; start ++) {
			service.execute(() -> {
				StringBuffer stringBuffer = new StringBuffer();
				for (int i=0; i < batch; i++){
						stringBuffer.append(getRandomString(4) + "," + random.nextInt() + "," + random.nextInt());
						stringBuffer.append("\r\n");
				}
				try {
					synchronized (bw) {
						bw.write(stringBuffer.toString());
						bw.flush();
						countDown.countDown();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			});
		}
		countDown.await();
		bw.close();
		System.out.println("insert finish");
		
		FileReader reader = new FileReader(file);
		BufferedReader br = new BufferedReader(reader);
		String line = null;
		int c = 0;
		
		Map<String, Integer> map = new HashMap<>(); 
//		CountDownLatch newCountDown = new CountDownLatch(count);
		
		int lineCount = 0;
		while((line = br.readLine()) != null) {
			final String[] infos = line.split("[,]");
//			service.execute(() -> {
				String start = infos[0].substring(0, 2);
				int yearSalary = Integer.parseInt(infos[1]) + Integer.parseInt(infos[2]);
				Integer s = map.get(start);
				if(s != null) {
					map.put(start, yearSalary + s);
				}else {
					map.put(start, yearSalary);
				}
//				newCountDown.countDown();
//			});
			++lineCount;
		}
//		newCountDown.await();
		System.out.println("line：" + lineCount);
		System.out.println("耗时:" + (System.currentTimeMillis() - startTime) + " ms");
		service.shutdown();
	}

	public static String getRandomString(int length){
		String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random=new Random();
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<length;i++){
			int number=random.nextInt(5);
			sb.append(str.charAt(number));
		}
		return sb.toString();
	}
}
